"""
LLM 配置模块
负责加载和管理 LLM 相关配置
"""

import os
from typing import Optional
from dataclasses import dataclass
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()


@dataclass
class LLMConfig:
    """LLM 配置类"""
    
    # API 配置
    api_key: str
    qdrant_host: str = "localhost"
    qdrant_port: int = 6333
    
    # 集合配置
    collection_name: str = "travel_documents"
    
    # 文档处理配置
    chunk_size: int = 1024
    chunk_overlap: int = 128
    
    # 检索配置
    similarity_top_k: int = 10
    keyword_top_k: int = 5
    
    def __init__(self):
        """初始化配置"""
        # 从环境变量获取 API 密钥
        self.api_key = os.getenv("DASHSCOPE_API_KEY")
        if not self.api_key:
            raise ValueError("未找到 DASHSCOPE_API_KEY 环境变量，请在 .env 文件中设置")
        
        # 从环境变量获取其他配置（可选）
        self.qdrant_host = os.getenv("QDRANT_HOST", "localhost")
        self.qdrant_port = int(os.getenv("QDRANT_PORT", "6333"))
        self.collection_name = os.getenv("COLLECTION_NAME", "travel_documents")
        
        # 文档处理配置
        self.chunk_size = int(os.getenv("CHUNK_SIZE", "1024"))
        self.chunk_overlap = int(os.getenv("CHUNK_OVERLAP", "128"))
        
        # 检索配置
        self.similarity_top_k = int(os.getenv("SIMILARITY_TOP_K", "10"))
        self.keyword_top_k = int(os.getenv("KEYWORD_TOP_K", "5"))
    
    def validate(self) -> bool:
        """
        验证配置是否有效
        
        Returns:
            配置是否有效
        """
        try:
            # 检查必要的配置
            if not self.api_key:
                return False
            
            if not self.qdrant_host:
                return False
            
            if self.qdrant_port <= 0:
                return False
            
            if not self.collection_name:
                return False
            
            return True
            
        except Exception:
            return False
    
    def __str__(self) -> str:
        """返回配置的字符串表示"""
        return f"LLMConfig(api_key={'*' * 8}, qdrant_host={self.qdrant_host}, qdrant_port={self.qdrant_port}, collection_name={self.collection_name})"
